<template>
  <div class="statistics-container">
    <div class="page-header">
      <h1>数据统计</h1>
      <p>查看系统运营数据和趋势分析</p>
    </div>

    <!-- 总览卡片 -->
    <div class="overview-cards">
      <el-card class="stat-card" v-for="card in overviewCards" :key="card.key">
        <div class="card-content">
          <div class="card-icon" :style="{ backgroundColor: card.color + '20', color: card.color }">
            <el-icon :size="24">
              <component :is="card.icon" />
            </el-icon>
          </div>
          <div class="card-info">
            <div class="card-value">{{ card.value }}</div>
            <div class="card-label">{{ card.label }}</div>
            <div class="card-trend" :class="card.trend > 0 ? 'positive' : 'negative'" v-if="card.trend !== undefined">
              <el-icon><component :is="card.trend > 0 ? 'CaretTop' : 'CaretBottom'" /></el-icon>
              {{ Math.abs(card.trend) }}%
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <el-row :gutter="20">
        <!-- 批次状态分布 -->
        <el-col :xs="24" :md="12">
          <el-card class="chart-card">
            <template #header>
              <h3>批次状态分布</h3>
            </template>
            <div class="chart-placeholder">
              <el-icon :size="64" style="color: #ddd;">
                <PieChart />
              </el-icon>
              <p>批次状态分布图表</p>
            </div>
          </el-card>
        </el-col>

        <!-- 月度趋势 -->
        <el-col :xs="24" :md="12">
          <el-card class="chart-card">
            <template #header>
              <h3>月度批次创建趋势</h3>
            </template>
            <div class="chart-placeholder">
              <el-icon :size="64" style="color: #ddd;">
                <TrendCharts />
              </el-icon>
              <p>月度趋势图表</p>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <!-- 茶叶品种分布 -->
        <el-col :xs="24" :md="12">
          <el-card class="chart-card">
            <template #header>
              <h3>茶叶品种分布</h3>
            </template>
            <div class="variety-stats">
              <div class="variety-item" v-for="variety in varietyStats" :key="variety.name">
                <div class="variety-info">
                  <span class="variety-name">{{ variety.name }}</span>
                  <span class="variety-count">{{ variety.count }} 批次</span>
                </div>
                <div class="variety-bar">
                  <div 
                    class="variety-progress" 
                    :style="{ width: variety.percentage + '%', backgroundColor: variety.color }"
                  ></div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 产地分布 -->
        <el-col :xs="24" :md="12">
          <el-card class="chart-card">
            <template #header>
              <h3>产地分布</h3>
            </template>
            <div class="origin-stats">
              <div class="origin-item" v-for="origin in originStats" :key="origin.name">
                <div class="origin-info">
                  <span class="origin-name">{{ origin.name }}</span>
                  <span class="origin-count">{{ origin.count }} 批次</span>
                </div>
                <div class="origin-bar">
                  <div 
                    class="origin-progress" 
                    :style="{ width: origin.percentage + '%', backgroundColor: origin.color }"
                  ></div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 最近活动 -->
    <el-card class="activity-card">
      <template #header>
        <h3>最近活动</h3>
      </template>
      <el-timeline>
        <el-timeline-item
          v-for="activity in recentActivities"
          :key="activity.id"
          :timestamp="activity.timestamp"
          :type="activity.type"
        >
          <div class="activity-content">
            <span class="activity-action">{{ activity.action }}</span>
            <span class="activity-target">{{ activity.target }}</span>
            <span class="activity-user">由 {{ activity.user }} 执行</span>
          </div>
        </el-timeline-item>
      </el-timeline>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { apiMethods } from '@/api'
import { ElMessage } from 'element-plus'
import { 
  Coffee, 
  TrendCharts, 
  PieChart,
  DataAnalysis,
  UserFilled,
  CaretTop,
  CaretBottom
} from '@element-plus/icons-vue'

const authStore = useAuthStore()

// 状态
const loading = ref(false)
const statistics = ref({
  totalBatches: 0,
  totalUsers: 0,
  todayBatches: 0,
  weeklyGrowth: 0
})

// 总览卡片数据
const overviewCards = computed(() => {
  const userRole = authStore.user?.role
  const cards = [
    {
      key: 'total-batches',
      label: '总批次数',
      value: statistics.value.totalBatches,
      icon: 'Coffee',
      color: '#409EFF',
      trend: 12.5
    }
  ]

  // 管理员可以看到所有统计
  if (userRole === 'admin') {
    cards.push(
      {
        key: 'total-users',
        label: '注册用户',
        value: statistics.value.totalUsers,
        icon: 'UserFilled',
        color: '#67C23A',
        trend: 8.3
      },
      {
        key: 'today-batches',
        label: '今日新增',
        value: statistics.value.todayBatches,
        icon: 'TrendCharts',
        color: '#E6A23C',
        trend: -2.1
      },
      {
        key: 'weekly-growth',
        label: '周活跃度',
        value: statistics.value.weeklyGrowth + '%',
        icon: 'DataAnalysis',
        color: '#F56C6C',
        trend: 5.7
      }
    )
  } else {
    // 其他角色看到相关的统计
    cards.push(
      {
        key: 'my-batches',
        label: '我的批次',
        value: statistics.value.myBatches || 0,
        icon: 'DataAnalysis',
        color: '#67C23A',
        trend: 15.2
      },
      {
        key: 'this-month',
        label: '本月处理',
        value: statistics.value.thisMonthProcessed || 0,
        icon: 'TrendCharts',
        color: '#E6A23C',
        trend: 3.8
      }
    )
  }

  return cards
})

// 茶叶品种统计
const varietyStats = ref([
  { name: '龙井茶', count: 15, percentage: 60, color: '#409EFF' },
  { name: '铁观音', count: 8, percentage: 32, color: '#67C23A' },
  { name: '普洱茶', count: 5, percentage: 20, color: '#E6A23C' },
  { name: '碧螺春', count: 3, percentage: 12, color: '#F56C6C' },
  { name: '其他', count: 2, percentage: 8, color: '#909399' }
])

// 产地分布统计
const originStats = ref([
  { name: '浙江省', count: 18, percentage: 72, color: '#409EFF' },
  { name: '福建省', count: 10, percentage: 40, color: '#67C23A' },
  { name: '云南省', count: 6, percentage: 24, color: '#E6A23C' },
  { name: '江苏省', count: 4, percentage: 16, color: '#F56C6C' },
  { name: '其他', count: 3, percentage: 12, color: '#909399' }
])

// 最近活动
const recentActivities = ref([
  {
    id: 1,
    action: '创建批次',
    target: 'TEA2024004 - 新品龙井',
    user: '农民张三',
    timestamp: '2024-08-27 14:30',
    type: 'success'
  },
  {
    id: 2,
    action: '更新物流',
    target: 'TEA2024003 - 云南普洱',
    user: '物流李四',
    timestamp: '2024-08-27 13:45',
    type: 'primary'
  },
  {
    id: 3,
    action: '确认销售',
    target: 'TEA2024002 - 安溪铁观音',
    user: '商家王五',
    timestamp: '2024-08-27 12:20',
    type: 'warning'
  },
  {
    id: 4,
    action: '溯源查询',
    target: 'TEA2024001 - 西湖龙井',
    user: '消费者刘六',
    timestamp: '2024-08-27 11:10',
    type: 'info'
  }
])

// 方法
const loadStatistics = async () => {
  loading.value = true
  try {
    // 这里应该调用实际的统计API
    // const response = await apiMethods.statistics.getOverview()
    // statistics.value = response.data.data
    
    // 模拟数据
    statistics.value = {
      totalBatches: 156,
      totalUsers: 89,
      todayBatches: 3,
      weeklyGrowth: 85.6,
      myBatches: 12,
      thisMonthProcessed: 28
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
    ElMessage.error('加载统计数据失败')
  } finally {
    loading.value = false
  }
}

// 生命周期
onMounted(() => {
  loadStatistics()
})
</script>

<style scoped>
.statistics-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  color: #2c3e50;
  margin-bottom: 10px;
}

.page-header p {
  color: #606266;
  font-size: 14px;
}

.overview-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  cursor: pointer;
  transition: transform 0.3s;
}

.stat-card:hover {
  transform: translateY(-4px);
}

.card-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.card-info {
  flex: 1;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 4px;
}

.card-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.card-trend {
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 2px;
}

.card-trend.positive {
  color: #67c23a;
}

.card-trend.negative {
  color: #f56c6c;
}

.charts-section {
  margin-bottom: 30px;
}

.chart-card {
  height: 300px;
}

.chart-placeholder {
  height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
}

.chart-placeholder p {
  margin-top: 12px;
  font-size: 14px;
}

.variety-stats, .origin-stats {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.variety-item, .origin-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.variety-info, .origin-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.variety-name, .origin-name {
  font-weight: 500;
  color: #2c3e50;
}

.variety-count, .origin-count {
  font-size: 12px;
  color: #909399;
}

.variety-bar, .origin-bar {
  height: 6px;
  background-color: #f5f7fa;
  border-radius: 3px;
  overflow: hidden;
}

.variety-progress, .origin-progress {
  height: 100%;
  border-radius: 3px;
  transition: width 0.3s;
}

.activity-card {
  margin-bottom: 20px;
}

.activity-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.activity-action {
  font-weight: 500;
  color: #2c3e50;
}

.activity-target {
  color: #409eff;
  font-size: 14px;
}

.activity-user {
  font-size: 12px;
  color: #909399;
}

@media (max-width: 768px) {
  .statistics-container {
    padding: 10px;
  }

  .overview-cards {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .card-content {
    gap: 12px;
  }

  .card-icon {
    width: 50px;
    height: 50px;
  }

  .card-value {
    font-size: 20px;
  }
}
</style>